import { FC, ReactNode, useContext, useImperativeHandle } from "react"
import { GlobalContext } from "../config/globalContext"
import { getClassNames, isUndefined, isNull } from "#/utils/tools"
import { SearchColumnType, SearchPropsType } from "./interface"
import Form from "../Form"
import InputText from "../Input/InputText"
import InputNumber from "../Input/InputNumber"
import Button from "../Button"

const Search: FC<SearchPropsType> = (props, ref) => {


  const {
    classNamePrefix
  } = useContext(GlobalContext);

  const prefixCls = `${classNamePrefix}-search`

  const {
    className = '',
    columns,
    formProps,
    actionRef,
    reset: resetProps,
    search: searchProps,
  } = props

  const classNamesObj = {
    search: getClassNames([
      `${prefixCls}`,
      className
    ])
  }

  const [form] = Form.useForm()


  const getInput = (column: SearchColumnType) => {
    const types: Record<SearchColumnType['type'], ReactNode> = {
      number: <InputNumber />,
      text: <InputText />
    }
    return types[column.type]
  }

  const reset = () => {
    let resetData: Record<string, any> = {}
    columns.forEach(e => {
      resetData[e.formItem.name] = ''
    })
    form.setFieldsValue(resetData)
    resetProps?.()
  }

  const search = () => {
    let searchData: any = {}
    let obj = form.getFields()
    Object.keys(obj).forEach((key: string) => {
      let value = obj[key]
      if (value !== '' && !isUndefined(value) && !isNull(value)) {
        searchData[key] = value
      }
    })
    console.log('searchData', searchData);

    searchProps?.(searchData)
  }

  useImperativeHandle(actionRef, () => ({
    search: () => {
      search()
    },
    reset: () => {
      reset()
    },
  }));


  return (
    <div className={classNamesObj.search}>
      <Form
        form={form}
        layout="vertical"
        columns={4}
        {...formProps}
      >
        {columns.map((column, index) => {
          return (
            <div key={column.formItem.name}>
              <Form.Item {...column.formItem}>
                {getInput(column)}
              </Form.Item>
            </div>
          )
        })}
      </Form>
      <div className="flex justify-end gap10 mtbase">
        <Button
          type="secondary"
          onClick={() => reset()}
        >重置</Button>
        <Button
          type="primary"
          onClick={() => search()}
        >搜索</Button>
      </div>
    </div>
  )
}
export default Search